<template>
    <el-row>
        <el-col :span="24" style="padding: 24px;">
            <el-button icon="Plus" @click="createInventoryType" type="primary">新建类型</el-button>
            <el-button icon="Refresh" @click="getList">刷新列表</el-button>
        </el-col>
    </el-row>
    <el-row>
        <el-col :span="24" style="padding:12px; min-height: 400px; height: 70vh;">
            <el-table v-loading="loading" :data="dataList" style="width: 80%; min-width: 600px; height: 100%;">
                <el-table-column label="类型名称" align="center" prop="name"></el-table-column>
                <el-table-column label="出入库类型" align="center">
                    <template #default="scope">
                        <el-tag :type="isInventoryIn(scope.row.inOutType) ? 'success' : 'warning'">
                            {{ isInventoryIn(scope.row.inOutType) ? '入库' : '出库' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="系统类型" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.isPlatfromType ? 'info' : ''">
                            {{ scope.row.isPlatfromType ? '系统' : '自定义' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="300" align="center" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <template v-if="scope.row.isPlatfromType">
                            - -
                        </template>
                        <template v-else>
                            <el-link :underline="false" style="margin-left: 24px;" type="primary"
                                @click="deleteType(scope.row)">
                                删除
                            </el-link>
                            <el-link :underline="false" style="margin-left: 24px;" type="primary"
                                @click="openDialog(true, scope.row)">
                                编辑
                            </el-link>
                        </template>
                    </template>
                </el-table-column>
            </el-table>
        </el-col>
    </el-row>

    <div style="width: 80%; min-width: 600px; margin: 0 auto; padding: 0;">
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />
    </div>

    <!-- 新建/编辑出入库类型弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑出入库类型' : '新建出入库类型'" width="500" draggable align-center
        :before-close="handleCloseDialog">
        <div>
            <el-form ref="typeFormRef" label-suffix=":" :model="formData" :rules="formRules" label-width="120px"
                style="max-width: 600px">

                <!-- 类型名称 -->
                <el-form-item label="类型名称" prop="name">
                    <el-input v-model="formData.name" />
                </el-form-item>

                <!-- 出入库类型 -->
                <el-form-item label="出入库类型" prop="inOutType">
                    <el-select v-model="formData.inOutType" placeholder="请选择类型"
                        :disabled="isEdit && formData.isPlatfromType">
                        <el-option v-for="type in inOutTypeOptions" :key="type.value" :label="type.label"
                            :value="type.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <!-- 系统类型提示 -->
                <el-form-item label="类型" v-if="formData.isPlatfromType">
                    <el-tag type="info">系统类型</el-tag>
                    <span style="margin-left: 10px; color: #999">系统类型不可修改</span>
                </el-form-item>
            </el-form>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="submitForm" type="primary" :loading="submitLoading">
                    提交
                </el-button>
                <el-button @click="handleCloseDialog" :disabled="submitLoading">
                    取消
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { InventoryUiAction } from '../../public/engine/uiAction/inventoryUiAction'
import { Definition } from '../../public/engine/common/definition'
import { DataPage } from '../../public/network/communicationConverter'
import { useRouter } from 'vue-router'
import { InventoryInOutType } from '../../public/engine/inventory/inventory'
import { InventoryType } from '../../public/engine/inventory/inventoryType'
import { NetworkParser } from '../../public/network/communicationConverter'
import { Engine } from '../../public/engine/engine'


export default {
    name: 'inventoryTypes',
    components: {
    },
    data() {
        return {
            total: 0,
            loading: false,
            queryParams: {
                pageNum: 1,
                pageSize: Definition.gDefualPageSize,
            },
            dataList: [],
            inventoryUiAction: new InventoryUiAction(),
            router: useRouter(),
            inOutType: InventoryInOutType.Uknown, // 默认不设置类型

            // Add these new properties for the dialog
            dialogVisible: false,
            isEdit: false,
            submitLoading: false,
            formData: {
                id: '',
                name: '',
                inOutType: InventoryInOutType.In,
                isPlatfromType: false,
                code: ''
            },
            formRules: {
                name: [
                    { required: true, message: '请输入类型名称', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                inOutType: [
                    { required: true, message: '请选择出入库类型', trigger: 'change' }
                ]
            },
            inOutTypeOptions: [
                { value: InventoryInOutType.In, label: '入库' },
                { value: InventoryInOutType.Out, label: '出库' }
            ]
        }
    },
    created() {
        // Get type from route query
        const type = this.$route.query.type
        if (type === 'in') {
            this.inOutType = InventoryInOutType.In
        } else if (type === 'out') {
            this.inOutType = InventoryInOutType.Out
        }
        else {
            this.inOutType = InventoryInOutType.Uknown
        }
    },


    methods: {

        isInventoryIn(type) {
            return type === InventoryInOutType.In
        },
        async getList() {
            try {
                this.loading = true
                const res = await this.inventoryUiAction.getInventoryTypeData({
                    pageInfo: new DataPage(this.queryParams.pageNum, 0, this.queryParams.pageSize),
                    inOutType: this.inOutType
                })

                if (res && res.data && res.data.dataList) {
                    this.dataList = res.data.dataList
                    this.total = res.data.pageInfo?.total || res.data.dataList.length
                } else if (res?.resErr) {
                    ElMessage.error('获取类型列表失败')
                }
            } catch (error) {
                console.error('获取类型列表失败', error)
                ElMessage.error('获取类型列表失败')
            } finally {
                this.loading = false
            }
        },

        createInventoryType() {
            this.openDialog(true);
        },
        handleTypeUpdated() {
            this.getList();
        },

        // Add these new methods for dialog handling
        openDialog(editMode = false, rowData = null) {
            this.isEdit = editMode
            this.dialogVisible = true

            if (editMode && rowData) {
                this.formData = {
                    id: rowData.id,
                    name: rowData.name,
                    inOutType: rowData.inOutType,
                    isPlatfromType: rowData.isPlatfromType,
                    code: rowData.code
                }
            } else {
                this.resetForm()
            }
        },

        resetForm() {
            this.formData = {
                id: '',
                name: '',
                inOutType: InventoryInOutType.In,
                isPlatfromType: false
            }

            if (this.$refs.typeFormRef) {
                this.$refs.typeFormRef.resetFields()
            }
        },

        handleCloseDialog() {
            if (!this.submitLoading) {
                this.dialogVisible = false
            }
        },

        async submitForm() {
            try {
                this.submitLoading = true
                await this.$refs.typeFormRef.validate()

                const typeData = new InventoryType({
                    id: this.formData.id,
                    name: this.formData.name,
                    inOutType: this.formData.inOutType,
                    code: this.formData.code,
                })

                let apiResult = null
                apiResult = await this.inventoryUiAction.updateOrCreateInventoryType({
                    orgId: Engine.profile.org.orgId,
                    inventoryType: typeData,
                    inoutType: this.formData.inOutType
                })

                if (apiResult.data || apiResult.resErr == null) {
                    ElMessage.success(this.isEdit ? '更新成功' : '创建成功')
                    this.dialogVisible = false
                    this.getList()
                } else if (apiResult.resErr) {
                    ElMessage.error(apiResult.resErr)
                }
            } catch (error) {
                if (error !== 'validate') {
                    console.error('提交失败', error)
                    ElMessage.error('提交失败')
                }
            } finally {
                this.submitLoading = false
            }
        },

        async deleteType(type) {
            try {
                await ElMessageBox.confirm(
                    `确认删除出入库类型"${type.name}"?`,
                    '提示',
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                )

                const apiResult = await this.inventoryUiAction.delInventoryType({
                    typeId: type.id
                })

                if (apiResult.data || apiResult.resErr == null) {
                    ElMessage.success('删除成功')
                    this.getList()
                } else if (apiResult.resErr) {
                    ElMessage.error(apiResult.resErr)
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除失败', error)
                    ElMessage.error('删除失败')
                }
            }
        },

        // Modify the action methods in the table column
        action(type, actionType) {
            if (actionType === 'edit') {
                this.openDialog(true, type)
            } else if (actionType === 'delete') {
                this.deleteType(type)
            }
        }
    },
    mounted() {
        this.getList()       
    },
}
</script>